package BlogMybatis.blog.controller.admin;



import BlogMybatis.blog.pojo.Type;
import BlogMybatis.blog.service.TypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Brandt
 * @since 2020-06-07
 */
@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;


    //后台分类列表
    @GetMapping("/types")
    public String types(@RequestParam(required = false,defaultValue = "1") int pageNum, Model model){
        PageHelper.startPage(pageNum,5);
        List<Type> listType = typeService.list();
        PageInfo<Type> pageInfo = new PageInfo<>(listType);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/types";
    }

    //跳到添加分类页
    @GetMapping("/types/add")
    public String toAddType(Model model){
        Type type = new Type();
        model.addAttribute("type",type);
        return "admin/types-input";
    }

    //新增分类名称
    @PostMapping("/types")
    public String addType(Type type, RedirectAttributes attributes){
        Type t = typeService.getTypeByName(type.getName());
        if(t != null){
            attributes.addFlashAttribute("message","不能添加重复的分类名称");
            return "redirect:/admin/types/add";
        }else {
            attributes.addFlashAttribute("message","添加成功");
        }
        typeService.save(type);
        return"redirect:/admin/types";
    }

    //根据id跳到编辑页面
    @GetMapping("/types/{id}/input")
    public String toEditType(@PathVariable Long id,Model model){
        model.addAttribute("type",typeService.getById(id));
        return "admin/types-input";
    }

    //修改分类
    @PostMapping("/types/{id}")
    public String editType(@PathVariable Long id, Type type, RedirectAttributes attributes){
        QueryWrapper<Type> wrapper = new QueryWrapper<>();
        wrapper.eq("name",type.getName());
        Type t = typeService.getOne(wrapper);
        if(t != null){
            attributes.addFlashAttribute("message","该分类名称已存在，不能重复添加");
            return "redirect:/admin/types/{id}/input";
        }else {
            attributes.addFlashAttribute("message","修改成功");
        }
        typeService.updateById(type);
        return "redirect:/admin/types";
    }

    //删除分类
    @GetMapping("/types/{id}/delete")
    public String deleteType(@PathVariable Long id,RedirectAttributes attributes){
        typeService.removeById(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/types";
    }
}

